package com.tao.auto.batchtao.message;

import com.tao.auto.batchtao.base.PhoneMessageCode;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author GLNC-taowenchen
 */
@Component
@EnableScheduling
public class DefaultPhoneMessageCodeImpl implements PhoneMessageCode<String> {
    private RestTemplate restTemplate;

    public DefaultPhoneMessageCodeImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public String phone() {
        return getPhone();
    }

    @Override
    public String code(String s) {
        int count = 5;
        return getCode(s, count);
    }

    String getPhone() {
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://119.29.88.137:8001/api/yh_qh/id={id}&operator=0&Region=0&card=2&phone=&loop=1&token={token}", String.class, "14761", this.token);
        String[] split = forEntity.getBody().split("\\|");
        if (split.length == 2 && "1".equals(split[0])) {
            return split[1];
        } else {
            return null;
        }
    }


    String getCode(String phone, int count) {
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://119.29.88.137:8001/api/yh_qm/id={id}&phone={phone}&t=zxl8899&token={token}", String.class, "14761", phone, this.token);
        String[] split = forEntity.getBody().split("\\|");
        if (split.length == 2 && "1".equals(split[0])) {
            return split[1];
        } else {
            if (count <= 0) {
                return null;
            }
            count--;
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCode(phone, count);
        }
    }

    @PostConstruct
    @Scheduled(fixedDelay = 1000 * 60 * 60 * 1)
    public void init() {
        token();
    }

    void token() {
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://119.29.88.137:8001/api/sign/username={username}&password={password}", String.class, "zxl8899", "zxl123456");
        String[] split = forEntity.getBody().split("\\|");
        if (split.length == 2 && "1".equals(split[0])) {
            token = split[1];
        } else {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            token();
        }
    }

    private String token;


}
